/**
 * 
 */

package com.shy.portal.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shy.base.controller.AbsController;
import com.shy.base.shiro.PasswordHelper;
import com.shy.base.shiro.UserRealm;
import com.shy.base.util.BeanUtil;
import com.shy.base.util.StringUtils;
import com.shy.base.vo.AppConstants;
import com.shy.base.vo.EasyuiPagerVo;
import com.shy.base.vo.PagerFilter;
import com.shy.portal.entity.User;
import com.shy.portal.service.UserService;

/**
 * <p>
 * Title: ManagerController
 * </p>
 * <p>
 * Description:用户操作控制器
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author H2013788
 */
@Controller
@RequestMapping("/user")
public class UserController extends AbsController {
    
	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());

    /**
     * userservice层
     */
    @Resource
    private UserService userService;
    
    @Autowired
    private UserRealm userRealm;

    /**
     * 请求用户列表页面
     * 
     * @return 用户页面
     * @author H2013788
     * @date 2017/9/27下午5:05:33
     */
    @RequestMapping("/list_page")
    public String showUserListPage(Model model) {
        if(SecurityUtils.getSubject().hasRole("admin") || SecurityUtils.getSubject().hasRole("manager")){
            //飛管理员或人資用户，默認只能修改個人密码
            model.addAttribute("isManager", true);
        }
        return "portal/user_list";
    }

    /**
     * 異步加载用户列表数据，由於easyui页面数据加载通过js
     * load方式，要求json格式，所以需要先请求到页面，然後再加载数据（此方式後面不再贅述）
     * 
     * @param user
     *            查询條件
     * @param page
     *            分頁查询頁数
     * @param rows
     *            每頁显示條数
     * @author H2013788
     * @date 2017/9/27下午5:05:59
     */
    @RequestMapping("/list_data")
    public void loadUserList(User user, Integer page, Integer rows, HttpServletResponse response) {
        if(!SecurityUtils.getSubject().hasRole("admin") && !SecurityUtils.getSubject().hasRole("manager")){
            //非管理员或人資用户，默認只能修改個人密码
            user.setUsername(getShiroUser().getLoginName());
        }
        PagerFilter pagerFilter = getPageable(rows == null ? 10L : rows);
        pagerFilter.setPagePer(null == page ? 1 : page);
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("id", "asc");
        pagerFilter.setOrderby(orderby);
        
        String[] likes = { "username", "realName" }; 
        Map<String, String[]> filterMap = new HashMap<>();
        filterMap.put(AppConstants.LIKE_TYPES, likes);
        
        pagerFilter = userService.listByPager(user, filterMap, pagerFilter);
        writeResponse(new StringBuffer(gsonDateTimeExpose.toJson(new EasyuiPagerVo(pagerFilter))), response);
    }

    /**
     * 用户預编辑，按照ID查询用户信息
     * 
     * @param id 用户ID
     * @author H2013788
     * @date 2017/10/6上午9:15:55
     */
    @RequestMapping("/edit_user")
    public void editUser(Integer id, HttpServletResponse response) {
        if (null != id) {
            User user = userService.getById(id);
            writeResponse(new StringBuffer(gsonDateTimeExpose.toJson(user)), response);
        } else {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.GET_OBJECT_NULL), response);
        }
    }

    /**
     * 保存用户信息，用於新增或编辑用户，另注意修改密码请獨立操作
     * 
     * @param user 用户實体
     * @author H2013788
     * @date 2017/9/29下午2:27:44
     */
    //@RequiresPermissions("user_add")
    @RequiresPermissions(value = {"user_add", "user_edit"}, logical = Logical.OR)
    @RequestMapping("/save_user")
    public void saveUser(User user, HttpServletResponse response) {
        if (null == user) {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
        } else {
            try {
                if (null != user.getId()) {
                    User old = userService.getById(user.getId());
                    BeanUtil.merge(old, user);
                    userService.update(old);
                    respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.SAVE_SUCCESS), response);
                } else {
                    //默認密码為用户名
                    User old = userService.getUserByName(user.getUsername());
                    if(old != null){
                        //用户已存在
                        respEasyuiErrorResult("用户已存在！", response);
                    }else{
                        user.setPassword(user.getUsername());
                        user.setSalt(UUID.randomUUID().toString());
                        // 按照shiro方式加密密码
                        new PasswordHelper().encryptPassword(user);
                        user.setStatus(1);
                        user.setCreateTime(new Date());
                        Subject subject = SecurityUtils.getSubject();
                        User loginUser = (User) subject.getSession().getAttribute("loginUser"); // 從Session中获取登錄信息實体
                        user.setCreateUser(loginUser.getUsername()); // 获取当前登錄人用户名
                        userService.save(user);
                        respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.SAVE_SUCCESS), response);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.SAVE_ERROR), response);
                logger.error("user save error:" + e);
            }
        }

    }

    /**
     * 刪除指定用户
     * 
     * @param id 用户ID
     * @author H2013788
     * @date 2017/10/6上午11:18:12
     */
    @RequestMapping("delete_user")
    public void deleteUser(Integer id, HttpServletResponse response) {
        try {
            if (null != id) {
                userService.deleteById(id);
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
            } else {
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
            logger.error(AppConstants.configMap.get(AppConstants.DELETE_ERROR) + e);
        }
    }
    
    /**
     * 重置密码
     * @param id
     * @author H2013788
     * @date 2018/9/19
     */
    @RequestMapping("resetPassword")
    public void resetPassword(Integer id, HttpServletResponse response){
        if(null != id){
            User user = userService.getById(id);
            if(null != user){
                try {
                	user.setPassword(user.getUsername());
                	user.setSalt(UUID.randomUUID().toString());
                    // 按照shiro方式加密密码
                    new PasswordHelper().encryptPassword(user);
                    user.setCreateTime(new Date());
                    Subject subject = SecurityUtils.getSubject();
                    User loginUser = (User) subject.getSession().getAttribute("loginUser"); // 從Session中获取登錄信息實体
                    user.setCreateUser(loginUser.getUsername()); // 获取当前登錄人用户名
                    userService.update(user);
                    respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
                } catch (Exception e) {
                    e.printStackTrace();
                    respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
                    logger.error(AppConstants.configMap.get(AppConstants.OPERATE_ERROR) + e);
                }
            }else{
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        }else{
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
        }
    }
    
    /**
     * 員工自行修改密码
     * @param id
     * @param password
     * @param newPassword
     * @param response
     * @author H2013788
     * @date 2018/9/19
     */
    @RequestMapping("modifyPassword")
    public void modifyPassword(String username, String password, String newPassword, HttpServletResponse response){
        if(StringUtils.isNotEmpty(username) && username.equals(getShiroUser().getLoginName())){
            User user = userService.getUserByName(username);
            if(null != user){
                User temp = new User();
                temp.setUsername(user.getUsername());
                temp.setPassword(password);
                temp.setSalt(user.getSalt());
                new PasswordHelper().encryptPassword(temp);
                //获取加密後的password
                if(user.getPassword().equals(temp.getPassword())){
                    user.setPassword(newPassword);
                    //user.setPasswordStr(newPassword);
                    // 按照shiro方式加密密码
                    new PasswordHelper().encryptPassword(user);
                    try {
                        userService.update(user);
                        respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
                        logger.error(AppConstants.configMap.get(AppConstants.OPERATE_ERROR) + e);
                    }
                }else{
                    //原密码校驗失败
                    respEasyuiErrorResult("原密码校驗失败！", response);
                }
            }else{
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        }else{
            respEasyuiErrorResult("登錄用户與修改用户不匹配！", response);
        }
    }
    
    
    /**
     * 清除shiro权限驗證緩存
     * @param empNo
     * @param response
     * @author H2013788
     * @date 2018/10/23
     */
    @RequestMapping("refreshAuth")
    public void refreshAuth(String empNo, HttpServletResponse response){
        if(StringUtils.isNotEmpty(empNo)){
            userRealm.removeUserCache(empNo);
            respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
        }else{
            respEasyuiErrorResult("用户信息异常，请核對！", response);
        }
    }
    
}
